<template>
  <el-dialog
    v-model="visible"
    :title="titleMap[detailsType]"
    width="600px"
    :before-close="handleCancel"
  >
    <el-form ref="postFormRef" :model="postForm" :rules="postFormRules" label-width="120px">
      <el-form-item label="登录手机号：" prop="username">
        <el-input
          v-model="postForm.username"
          :disabled="detailsType == 2"
          placeholder="请输入手机号"
          name="username"
          size="large"
          type="text"
          show-word-limit
          maxlength="11"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="name">
        <el-input
          v-model="postForm.name"
          name="name"
          size="large"
          type="text"
          placeholder="请输入用户名称"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="角色：" prop="roleType">
        <el-radio-group v-model="postForm.roleType">
          <el-radio :value="2">管理员</el-radio>
          <el-radio :value="3">普通成员</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { FormInstance, FormRules } from "element-plus";
import MemberManageAPI, { AddUserFormData, UserListInfo } from "@/api/memberManage";
// 定义 props
const props = defineProps({
  // 是否展示详情弹出框
  modelValue: {
    type: Boolean,
    default: false,
  },
  // 宽度
  width: {
    type: String,
    default: "50%",
  },
  // 详情
  detailsParam: {
    type: Object as PropType<UserListInfo>,
    default: () => ({
      createdAt: "",
      lastLoginAt: "",
      name: "",
      roleType: 3,
      username: "",
    }),
  },
  // 详情类型 1：新增成员  2：修改成员
  detailsType: {
    type: Number,
    default: 1,
  },
});
// 标题名称
const titleMap: Record<number, string> = {
  1: "新增成员",
  2: "修改成员",
};
// 表单Ref
const postFormRef = ref<FormInstance>();
// 表单数据
const postForm = ref<AddUserFormData>({
  name: "",
  roleType: 3,
  username: "",
});
// 表单规则
const postFormRules = ref<FormRules<AddUserFormData>>({
  username: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("电话号码不能为空"));
        } else if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的电话号码"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  roleType: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择角色"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
// 防止多次点击
const btnLoading = ref<boolean>(false);

// 定义 emits
const emit = defineEmits(["update:modelValue", "confirm", "cancel"]);
// 计算属性：用于双向绑定
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});
// 点击确认按钮
const handleConfirm = () => {
  // 验证表单参数是否正确
  postFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (btnLoading.value) return;
      btnLoading.value = true;
      if (props.detailsType == 1) {
        addUser();
      } else if (props.detailsType == 2) {
        updateUser();
      }
    } else {
      btnLoading.value = false;
    }
  });
};
// 新增用户接口
const addUser = () => {
  MemberManageAPI.addUser(postForm.value)
    .then(async (res) => {
      emit("confirm");
      visible.value = false;
      btnLoading.value = false;
      ElMessage.success("添加成功");
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
// 修改用户接口
const updateUser = () => {
  MemberManageAPI.updateUser(postForm.value)
    .then(async (res) => {
      emit("confirm");
      visible.value = false;
      btnLoading.value = false;
      ElMessage.success("修改成功");
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
// 点击取消按钮
const handleCancel = () => {
  emit("cancel");
  visible.value = false;
};
onMounted(() => {
  // 编辑时初始化参数
  if (props.detailsType == 2) {
    postForm.value.username = props.detailsParam.username;
    postForm.value.roleType = props.detailsParam.roleType;
    postForm.value.name = props.detailsParam.name;
    console.log(postForm.value);
  }
});
</script>

<style scoped lang="scss"></style>
